package com.bob.light.activity

import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.core.widget.addTextChangedListener
import com.bob.light.R
import com.bob.light.TuyaHomeSDKHelper
import com.bob.light.activity.delegate.ActivatorManagerDelegate
import com.bob.light.config.DeviceConfig
import com.bob.light.setOnSingleClickListener
import com.tuya.smart.home.sdk.builder.ActivatorBuilder
import com.tuya.smart.sdk.bean.DeviceBean
import kotlinx.android.synthetic.main.app_activator_ez_type.*
import kotlinx.android.synthetic.main.app_activity_activator_manager.*
import kotlinx.android.synthetic.main.app_title_bar.*

class ActivatorManagerActivity : AppCompatActivity() {

    private val mActivatorDelegate: ActivatorManagerDelegate? = ActivatorManagerDelegate()
    private var mCurrentHomeId: Long = -1

    companion object {

        @JvmStatic
        fun navigation(activity: AppCompatActivity?) {
            activity?.let { context ->
                val intent = Intent(context, ActivatorManagerActivity::class.java)
                context.startActivity(intent)
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.app_activity_activator_manager)
        mActivatorDelegate?.let {
            lifecycle.addObserver(it)
        }
        initView()
        initData()
    }

    private fun initView() {
        fl_back_pressed?.setOnSingleClickListener {
            finish()
        }
        tv_title_name?.text = title
        tv_home_name?.setOnSingleClickListener {
            FamilyManagerActivity.navigationForResult(this@ActivatorManagerActivity)
        }

        et_wifi_name?.addTextChangedListener ( afterTextChanged = {
            tv_wifi_connect_btn?.isEnabled = !(TextUtils.isEmpty(it) || TextUtils.isEmpty(et_wifi_pwd?.text) || (mCurrentHomeId < 1))
        })
        et_wifi_pwd?.addTextChangedListener ( afterTextChanged = {
            tv_wifi_connect_btn?.isEnabled = !(TextUtils.isEmpty(it) || TextUtils.isEmpty(et_wifi_name?.text) || (mCurrentHomeId < 1))
        })

        tv_device_manager?.setOnSingleClickListener {
            DeviceManagerActivity.navigation(this@ActivatorManagerActivity)
        }
    }

    /**
     * @desc 设备配网
     */
    private fun initData() {
        tv_wifi_connect_btn?.setOnSingleClickListener {
            queryToken { token ->
                val builder = initActivatorBuilder(token)
                mActivatorDelegate?.start(builder)
                tv_wifi_connect_btn?.text = "配置中. . ."
                tv_wifi_connect_btn?.isEnabled = false
            }
        }
        DeviceConfig.queryDeviceList().forEachIndexed { index, devResp ->
            if (index == 0) {
                ll_device_info?.visibility = View.VISIBLE
                tv_device_name?.text = (devResp?.name)?:""
            }
        }
    }

    private fun queryToken(block: (token: String) -> Unit) {
        TuyaHomeSDKHelper.queryActivatorToken(mCurrentHomeId) {
            block.invoke(it)
        }
    }

    private fun initActivatorBuilder(token: String): ActivatorBuilder {
        val ssid = (et_wifi_name?.text?.toString())?:""
        val pwd = (et_wifi_pwd?.text?.toString())?:""
        return TuyaHomeSDKHelper.createActivatorBuilder(this@ActivatorManagerActivity, ssid, pwd, token,
                stepCallback = { step: String? ->
                    executeStep(step)
                }, activeSuccessCallback = { devResp: DeviceBean? ->
                    mActivatorDelegate?.onActiveSuccess(devResp)
                    executeActiveSuccess(devResp)
                }, errorCallback = { errorMsg: String? ->
                    mActivatorDelegate?.onActiveError(errorMsg)
                    executeActiveFail()
                })
    }

    private fun executeStep(step: String?) {
        tv_wifi_connect_btn?.text = "$step"
    }

    private fun executeActiveSuccess(devResp: DeviceBean?) {
        tv_wifi_connect_btn?.text = "配置成功"
        tv_wifi_connect_btn?.isEnabled = true
        ll_device_info?.visibility = View.VISIBLE
        tv_device_name?.text = (devResp?.name)?:""
    }

    private fun executeActiveFail() {
        tv_wifi_connect_btn?.text = "重新配置"
        val isEnabled = !(TextUtils.isEmpty(et_wifi_name?.text) ||
                TextUtils.isEmpty(et_wifi_pwd?.text) || (mCurrentHomeId < 1))
        tv_wifi_connect_btn?.isEnabled = isEnabled
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == FamilyManagerActivity.REQUEST_CODE) {
            tv_home_name?.text = data?.getStringExtra(FamilyManagerActivity.HOME_NAME)?:"需要选择家庭"
            mCurrentHomeId = (data?.getLongExtra(FamilyManagerActivity.HOME_ID, -1L))?:-1L
        }
        super.onActivityResult(requestCode, resultCode, data)
    }

    override fun onDestroy() {
        super.onDestroy()
        mActivatorDelegate?.let {
            lifecycle.removeObserver(it)
        }
    }

}